package com.oracle.containers.map;

import java.util.Comparator;
import java.util.Map;
import java.util.TreeMap;

/**
 * @author zhouyanxiang
 * @create 2020-08-2020/8/17-11:18
 * TreeMap<K,V>的Key值是要求实现java.lang.Comparable，所以迭代的时候TreeMap默认是按照Key值升序排序的；
 * TreeMap的实现是基于红黑树结构。适用于按自然顺序或自定义顺序遍历键（key）。
 */
public class TreeMapReview {

    public static void main(String[] args) {

        MyComparator myComparator = new MyComparator();
        TreeMap<Integer, Integer> treeMap = new TreeMap<>(myComparator);


        for (int i = 0; i < 10; i++) {
            treeMap.put(i, 10*i );
        }
        for (int i = 0; i < 10; i++) {
            treeMap.put(2*i,  200*i );
        }

        for (Map.Entry<Integer,Integer> entry : treeMap.entrySet()){
            System.out.println(entry.getKey() + "\t" +entry.getValue());
        }
    }

    // 倒序输出
    static class MyComparator implements Comparator {

        @Override
        public int compare(Object o1, Object o2) {
            Integer parm1 = (Integer) o1;
            Integer parm2 = (Integer) o2;
            return -parm1.compareTo(parm2);
        }
    }

}
